import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Animated,
  Easing,
} from 'react-native';

import PropTypes from 'prop-types';

const animationDuration = 200;

class ToastContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      wrapperOpacity: new Animated.Value(0),
      wrapperScale: new Animated.Value(0.5),
      show: true,
    };
  }

  componentDidMount() {
    const {
      duration,
      animation,
    } = this.props;
    Animated.parallel([
      Animated.timing(this.state.wrapperOpacity, {
        toValue: 1,
        duration: 200,
        easing: animation,
      }),
      Animated.timing(this.state.wrapperScale, {
        toValue: 1,
        duration: 200,
        easing: animation,
      }),
    ]).start(() => {
      if (duration !== 'always') {
        this._timerOut1 = setTimeout(() => this._hide(), duration);
      }
    });
  }

  _hide = (callback) => {
    const {
      animation,
    } = this.props;
    Animated.parallel([
      Animated.timing(this.state.wrapperOpacity, {
        toValue: 0,
        duration: 200,
        easing: animation,
      }),
      Animated.timing(this.state.wrapperScale, {
        toValue: 0.5,
        duration: 200,
        easing: animation,
      }),
    ]).start(() => {
      typeof callback === 'function' && callback();
      this.setState({ show: false });
    });
  };

  render() {
    const {
      message,
      position,
      wrapperStyle,
      textStyle,
      addon,
    } = this.props;
    const {
      wrapperOpacity,
      wrapperScale,
      show,
    } = this.state;

    // default center
    const textPos = position === 'center' ? 'center' : position === 'top' ? 'flex-start' : 'flex-end';

    return (
      <View style={[styles.container, !show && { display: 'none' }]}>
        <Animated.View
          style={[
            {
              backgroundColor: 'rgba(0,0,0,.8)',
              paddingVertical: 10,
              paddingHorizontal: 12,
              borderRadius: 8,
              alignItems: 'center',
            },
            wrapperStyle,
            {
              opacity: wrapperOpacity,
              transform: [
                { scale: wrapperScale },
              ],
              alignSelf: textPos,
            },
          ]}>
          {addon}
          <Text style={[{ color: '#fff' }, textStyle]}>
            {message}
          </Text>
        </Animated.View>
      </View>
    );
  }
}

ToastContainer.propTypes = {
  message: PropTypes.string,
  position: PropTypes.oneOf([
    'top',
    'center',
    'bottom',
  ]),
};
ToastContainer.defaultProps = {
  message: '',
  position: 'center',
  animation: Easing.elastic(1),
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    paddingVertical: 50,
  },
});

export default ToastContainer;
